<script setup lang="ts">
import { FwbButton, FwbModal, FwbAccordion, FwbAccordionContent, FwbAccordionHeader, FwbAccordionPanel, FwbTabs, FwbTab } from 'flowbite-vue'
import RobotAvatar from '~/assets/img/robot-avatar.png';
import type { MessageType, SessionType } from '~/types/chat';

defineProps<{
    session?: SessionType,
}>();

const emits = defineEmits<{
    (e: 'change'): void,
}>();

const route = useRoute();
const { showToast } = useToast();
const { sendMsg, getMsgListBySessionId } = useChat();

// get from route
const session_id = computed(() => route.params.id as string);

const setting = ref(false);

const msg = ref('');

const msgList = ref<MessageType[]>([]);

const loading = ref(false);

const scrollViewRef = ref<HTMLDivElement>();

const getMsgList = async () => {
    try {
        loading.value = true;
        const { data } = await getMsgListBySessionId(session_id.value);
        msgList.value = data.list;
    }
    catch (e) {
        console.dir(e);
        if (e instanceof Error) showToast({ type: 'danger', msg: e.message });
    }
    finally {
        loading.value = false;
    }
};

// send answer to chat bot
const onSend = async () => {
    if (msg.value.trim() === '') {
        showToast({ msg: 'Please send a message with content!', type: 'warning' });
    } else {
        // generate question
        const question: MessageType = { content: msg.value, role: 'user', time: +new Date() };
        msgList.value.push(question);
        try {
            loading.value = true;
            // receive message
            await sendMsg(msg.value, session_id.value,
                () => msgList.value.push({ content: '', role: 'bot', time: +new Date() }),
                (msg: string) => msgList.value[msgList.value.length - 1].content += msg);
            emits('change');
        }
        catch (e) {
            if (e instanceof Error) {
                console.dir(e);
                showToast({ msg: e.message, type: 'danger' });
            }
        }
        finally {
            loading.value = false;
        }
    }
    msg.value = '';
};

// scroll to bottom
watch(msgList, () => {
    nextTick(() => {
        const h = scrollViewRef.value!.firstElementChild!.getBoundingClientRect().height;
        scrollViewRef.value!.scrollTo({ top: h, behavior: 'smooth' });
    });
}, { deep: true });

onMounted(async () => {
    getMsgList();
});
</script>

<template>
    <div class="p-2 w-full h-full bg-gradient-to-br from-theme/25 to-element/25 flex flex-col gap-2 overflow-x-hidden">
        <header class="px-2 w-full h-12 flex shrink-0 gap-3 overflow-x-hidden">
            <img class="w-12 aspect-square rounded" :src="RobotAvatar" />
            <h2 class="text-2xl leading-loose font-bold truncate">{{ $props.session?.title || 'New Chat' }}</h2>
        </header>
        <div ref="scrollViewRef" class="w-full flex-auto bg-white rounded-lg overflow-x-hidden overflow-y-scroll">
            <home-chat-panel :msg-list="msgList" />
        </div>
        <footer class="w-full flex gap-2">
            <fwb-button
                class="w-8 h-8 bg-transparent border-2 border-element hover:bg-theme flex justify-center items-center"
                @click="setting = true">
                <svg class="icon" aria-hidden="true" :style="{ width: '1rem', height: '1rem' }">
                    <use xlink:href="#icon-gear" />
                </svg>
            </fwb-button>
            <input v-model="msg" class="h-8 flex-auto rounded-lg indent-2 border-2 border-theme focus:outline-element
                 disabled:bg-slate-100 disabled:text-slate-400" :disabled="loading" @keydown.enter="onSend"
                placeholder="Send a message to mini bot." />
            <fwb-button :loading="loading" :disabled="loading" @click="onSend"
                class="w-16 h-8 rounded-lg bg-blue-600 flex justify-center items-center">
                <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-send-white" />
                </svg>
            </fwb-button>
        </footer>
    </div>

    <teleport to="body">
        <fwb-modal v-if="setting" size="lg" @close="setting = false" not-escapable persistent>
            <template #header>
                <div class="flex items-center text-lg">Mini Bot Settings</div>
            </template>
            <template #body>
                <fwb-accordion class="m-[-12px]" flush>
                    <fwb-accordion-panel>
                        <fwb-accordion-header>Chat Models</fwb-accordion-header>
                        <fwb-accordion-content>
                            <div class="m-[-12px]">
                                <fwb-tabs variant="underline" class="p-5">
                                    <fwb-tab name="DeepSeek" title="DeepSeek">
                                        DeepSeek
                                    </fwb-tab>
                                    <fwb-tab name="ChatBro" title="ChatBro">
                                        ChatBro
                                    </fwb-tab>
                                    <fwb-tab name="ChatBro" title="ChatBro">
                                        ChatBro
                                    </fwb-tab>
                                </fwb-tabs>
                            </div>
                        </fwb-accordion-content>
                    </fwb-accordion-panel>
                    <fwb-accordion-panel>
                        <fwb-accordion-header>Conversation Relevant</fwb-accordion-header>
                        <fwb-accordion-content>
                            <div>
                                <p class="mb-2 text-gray-500 dark:text-gray-400">
                                    Flowbite is first conceptualized and designed using the Figma software so everything
                                    you see in the library has a design equivalent in our Figma file.
                                </p>
                                <p class="text-gray-500 dark:text-gray-400">
                                    Check out the <a class="text-blue-600 dark:text-blue-500 hover:underline"
                                        href="https://flowbite.com/figma/">Figma design system</a> based on the utility
                                    classes from Tailwind CSS and components from Flowbite.
                                </p>
                            </div>
                        </fwb-accordion-content>
                    </fwb-accordion-panel>
                    <fwb-accordion-panel>
                        <fwb-accordion-header>and one more header</fwb-accordion-header>
                        <fwb-accordion-content>
                            <div>
                                <p class="mb-2 text-gray-500 dark:text-gray-400">
                                    Flowbite is first conceptualized and designed using the Figma software so everything
                                    you see in the library has a design equivalent in our Figma file.
                                </p>
                                <p class="text-gray-500 dark:text-gray-400">
                                    Check out the <a class="text-blue-600 dark:text-blue-500 hover:underline"
                                        href="https://flowbite.com/figma/">Figma design system</a> based on the utility
                                    classes from Tailwind CSS and components from Flowbite.
                                </p>
                            </div>
                        </fwb-accordion-content>
                    </fwb-accordion-panel>
                </fwb-accordion>
            </template>
            <template #footer>
                <div class="flex justify-between flex-row-reverse">
                    <fwb-button class="bg-element" @click="setting = false">Finish</fwb-button>
                </div>
            </template>
        </fwb-modal>
    </teleport>
</template>